//
//  MustLocation.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/3/11.
//  
  

#import "MustLocation.h"

@implementation MustLocation

+ (BOOL)runableWithMustLocation:(BOOL)isMust controller:(UIViewController *)ctrl {
    if (!isMust) {
        return YES;
    }
    CLAuthorizationStatus status = self.authorizationStatus;
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        return YES;
    }
    if (status == kCLAuthorizationStatusNotDetermined) {
        [SLLocationService startLocationWithCompletion:^(CGFloat lat, CGFloat lon) {
            [self runableWithMustLocation:isMust controller:ctrl];
        }];
        return NO;
    }
    [self openAppSettingsAlert:ctrl];
    return NO;
}

+ (void)openAppSettingsAlert:(UIViewController *)ctrl {
    NSString *message = @"To ensure a smooth loan application process, SulitLoan accesses your location. Please go to \"Settings\" and enable location services for SulitLoan.";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Unable to locate" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        }
    }];
    [alert addAction:confirmAction];
    [alert addAction:cancelAction];
    [ctrl presentViewController:alert animated:YES completion:nil];
}

+ (CLAuthorizationStatus)authorizationStatus {
    if (@available(iOS 14.0, *)) {
        return [CLLocationManager new].authorizationStatus;
    } else {
        return [CLLocationManager authorizationStatus];
    }
}


@end
